<template>
  <div class="page-container">
    <div class="page-header">
      <h2>{{ title }}</h2>
      <div class="header-actions">
        <button class="btn btn-secondary" @click="saveAsDraft">保存草稿</button>
        <button class="btn btn-primary" @click="publishTask">发布任务</button>
      </div>
    </div>

    <div class="task-form">
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="section-title">基本信息</h3>
        <div class="form-content">
          <div class="form-item">
            <label>任务名称</label>
            <input type="text" v-model="taskForm.title" placeholder="请输入任务名称" />
          </div>
          <div class="form-item">
            <label>任务类型</label>
            <select v-model="taskForm.type">
              <option value="vocabulary">词汇练习</option>
              <option value="reading">阅读理解</option>
              <option value="listening">听力训练</option>
              <option value="speaking">口语练习</option>
              <option value="writing">写作任务</option>
            </select>
          </div>
          <div class="form-row">
            <div class="form-item">
              <label>开始时间</label>
              <input type="datetime-local" v-model="taskForm.startTime" />
            </div>
            <div class="form-item">
              <label>截止时间</label>
              <input type="datetime-local" v-model="taskForm.endTime" />
            </div>
          </div>
        </div>
      </div>

      <!-- 任务内容 -->
      <div class="form-section">
        <h3 class="section-title">任务内容</h3>
        <div class="form-content">
          <div class="form-item">
            <label>任务说明</label>
            <textarea v-model="taskForm.description" placeholder="请输入任务说明" rows="4"></textarea>
          </div>
          <div class="form-item">
            <label>学习资源</label>
            <div class="resource-upload">
              <div class="upload-box" @click="triggerUpload">
                <i class="icon">📁</i>
                <span>点击上传资源</span>
                <input type="file" ref="fileInput" @change="handleFileUpload" multiple style="display: none" />
              </div>
              <div class="resource-list" v-if="taskForm.resources.length">
                <div class="resource-item" v-for="(item, index) in taskForm.resources" :key="index">
                  <i class="icon">📄</i>
                  <span class="resource-name">{{ item.name }}</span>
                  <i class="icon delete" @click="removeResource(index)">🗑️</i>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 发布选项 -->
      <div class="form-section">
        <h3 class="section-title">发布选项</h3>
        <div class="form-content">
          <div class="form-item">
            <label>选择班级</label>
            <div class="class-select">
              <div
                v-for="cls in classList"
                :key="cls.id"
                class="class-item"
                :class="{ active: taskForm.classes.includes(cls.id) }"
                @click="toggleClass(cls.id)"
              >
                {{ cls.name }}
              </div>
            </div>
          </div>
          <div class="form-item">
            <label class="checkbox-label">
              <input type="checkbox" v-model="taskForm.sendNotification" />
              发布后通知学生和家长
            </label>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { taskApi } from '@/api'

export default {
  name: 'CreateTask',
  data() {
    return {
      title: '创建任务',
      taskForm: {
        title: '',
        type: 'vocabulary',
        startTime: '',
        endTime: '',
        description: '',
        resources: [],
        classes: [],
        sendNotification: true
      },
      classList: [
        { id: 1, name: '初一(1)班' },
        { id: 2, name: '初一(2)班' },
        { id: 3, name: '初一(3)班' },
        { id: 4, name: '初二(1)班' },
        { id: 5, name: '初二(2)班' }
      ],
      isSubmitting: false
    }
  },
  mounted() {
    const task = this.$route.query.task
    if (task) {
      this.taskForm = JSON.parse(task)
      this.title = '编辑任务'
    }
  },
  methods: {
    validateForm() {
      if (!this.taskForm.title.trim()) {
        this.$message.warning('请输入任务名称')
        return false
      }
      if (!this.taskForm.startTime) {
        this.$message.warning('请选择开始时间')
        return false
      }
      if (!this.taskForm.endTime) {
        this.$message.warning('请选择截止时间')
        return false
      }
      if (new Date(this.taskForm.endTime) <= new Date(this.taskForm.startTime)) {
        this.$message.warning('截止时间必须晚于开始时间')
        return false
      }
      if (!this.taskForm.description.trim()) {
        this.$message.warning('请输入任务说明')
        return false
      }
      if (this.taskForm.classes.length === 0) {
        this.$message.warning('请选择至少一个班级')
        return false
      }
      return true
    },

    async saveAsDraft() {
      if (this.isSubmitting) return

      try {
        this.isSubmitting = true
        const resources = await this.uploadFiles()

        const draftData = {
          ...this.taskForm,
          resources,
          teacherId: JSON.parse(localStorage.getItem('user')).id
        }

        if (this.taskForm.id) {
          await taskApi.updateTask(this.taskForm.id, draftData)
        } else {
          await taskApi.createTask(draftData)
        }

        this.$message.success('草稿保存成功')
        this.$router.push('/teacher/tasks/manage')
      } catch (error) {
        console.error('保存草稿失败:', error)
        this.$message.error('保存草稿失败，请重试')
      } finally {
        this.isSubmitting = false
      }
    },

    async publishTask() {
      if (this.isSubmitting) return
      if (!this.validateForm()) return

      try {
        this.isSubmitting = true
        const resources = await this.uploadFiles()

        const taskData = {
          ...this.taskForm,
          resources,
          teacherId: JSON.parse(localStorage.getItem('user')).id
        }

        if (this.taskForm.id) {
          await taskApi.updateTask(this.taskForm.id, taskData)
        } else {
          await taskApi.createTask(taskData)
        }

        if (this.taskForm.sendNotification) {
          await this.sendNotifications()
        }

        this.$message.success('任务发布成功')
        this.$router.push('/teacher/tasks/manage')
      } catch (error) {
        console.error('发布任务失败:', error)
        if (error.code === 'ERR_NETWORK') {
          this.$message.error('网络连接失败，请确保json-server已启动')
        } else {
          this.$message.error('发布任务失败，请重试')
        }
      } finally {
        this.isSubmitting = false
      }
    },

    async uploadFiles() {
      // 这里模拟文件上传，实际项目中需要实现真实的文件上传逻辑
      return this.taskForm.resources.map((resource) => ({
        name: resource.name,
        url: URL.createObjectURL(resource.file),
        size: resource.file.size,
        type: resource.file.type
      }))
    },

    async sendNotifications() {
      // 这里实现发送通知的逻辑
      // 可以调用专门的通知API
      console.log('发送通知给学生和家长')
    },

    triggerUpload() {
      this.$refs.fileInput.click()
    },

    handleFileUpload(e) {
      const files = Array.from(e.target.files)
      this.taskForm.resources.push(
        ...files.map((file) => ({
          name: file.name,
          file
        }))
      )
    },

    removeResource(index) {
      this.taskForm.resources.splice(index, 1)
    },

    toggleClass(classId) {
      const index = this.taskForm.classes.indexOf(classId)
      if (index === -1) {
        this.taskForm.classes.push(classId)
      } else {
        this.taskForm.classes.splice(index, 1)
      }
    }
  }
}
</script>

<style scoped>
.page-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.btn {
  padding: 8px 16px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-primary {
  background: #409eff;
  color: white;
}

.btn-primary:hover {
  background: #66b1ff;
}

.btn-secondary {
  background: #f4f4f5;
  color: #606266;
}

.btn-secondary:hover {
  background: #e9e9eb;
}

.form-section {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  color: #303133;
  margin-bottom: 20px;
  font-weight: 500;
}

.form-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-row {
  display: flex;
  gap: 20px;
}

.form-row .form-item {
  flex: 1;
}

label {
  font-size: 14px;
  color: #606266;
}

input[type='text'],
input[type='datetime-local'],
select,
textarea {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

input[type='text']:focus,
input[type='datetime-local']:focus,
select:focus,
textarea:focus {
  border-color: #409eff;
  outline: none;
}

.resource-upload {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.upload-box {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 20px;
  border: 2px dashed #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-box:hover {
  border-color: #409eff;
  color: #409eff;
}

.resource-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.resource-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #eee;
}

.resource-name {
  flex: 1;
  font-size: 14px;
}

.delete {
  cursor: pointer;
}

.class-select {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.class-item {
  padding: 6px 12px;
  border-radius: 4px;
  background: #fff;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.class-item:hover {
  border-color: #409eff;
  color: #409eff;
}

.class-item.active {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

input[type='checkbox'] {
  width: 16px;
  height: 16px;
  cursor: pointer;
}
</style>
